package com.mall.activiti.service.impl;

import com.mall.activiti.Request.AddXMLReq;
import com.mall.activiti.service.ActivitiService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipInputStream;

@Service
public class ActivitiServiceImpl implements ActivitiService {

    @Autowired
    private RepositoryService repositoryService;

    @Override
    public Deployment uploadFileAndDeployment(MultipartFile processFile, String processName) {
        String originalFilename = processFile.getOriginalFilename();
        String extension = FilenameUtils.getExtension(originalFilename);
        if (processName != null) {
            processName = originalFilename;
        }
        Deployment deployment = null;
        try {
            InputStream inputStream = processFile.getInputStream();
            if ("zip".equals(extension)) {
                // 压缩包部署方式
                ZipInputStream zipInputStream = new ZipInputStream(inputStream);
                deployment = repositoryService.createDeployment().addZipInputStream(zipInputStream).name(processName).deploy();
            } else if ("bpmn".equals(extension)) {
                // bpmn文件部署方式
                deployment = repositoryService.createDeployment().addInputStream(originalFilename, inputStream).name(processName).deploy();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return deployment;
    }


    @Override
    public Deployment postBPMNAndDeployment(AddXMLReq addXMLRequest) {
        return repositoryService.createDeployment()
                // .addString 第一次参数的名字如果没有添加.bpmn的话，不会插入到 ACT_RE_DEPLOYMENT 表中
                .addString(addXMLRequest.getProcessName() + ".bpmn", addXMLRequest.getBpmnContent())
                .name(addXMLRequest.getProcessName())
                .deploy();
    }
}
